﻿Imports System.ComponentModel
Imports System.IO
Imports System.Text
Imports System.Data
Imports DealGpFile.SqlTable
Imports SQLite
Imports MiniExcelLibs
Imports System.Collections.Generic
Imports SQLite0 = System.Data.SQLite

Public Class Form1
    Private WithEvents bgWorkerImpFile As New BackgroundWorker()
    Private selectedFiles As String()
    Private dbDateDic As Dictionary(Of String, Long)

    Private Sub Bt_Imp_f_Click(sender As Object, e As EventArgs) Handles Bt_Imp_f.Click
        ' 选择数据
        Try
            Dim SelectFd As String = PickFolder(Me.FolderBrowserDialog1)
            If String.IsNullOrEmpty(SelectFd) Then
                AddInfo("No Folder select or Worker is busy")
                Exit Sub
            End If
            'selectedFiles = PickFile(Me.OpenFileDialog1, "txt", True)
            selectedFiles = Directory.EnumerateFiles(SelectFd, "*.csv", SearchOption.AllDirectories).ToArray
            ' 更新数据库已有数据
            'dbDateDic = updateDbList()
            ' 导入数据
            If selectedFiles.Length > 0 AndAlso Not bgWorkerImpFile.IsBusy Then
                bgWorkerImpFile.RunWorkerAsync(New ImportArguments With {
                    .IsFirstLine = True,
                    .Files = selectedFiles
                })
            Else
                AddInfo($"No csv files{SelectFd} ; or Worker is busy")
            End If
        Catch ex As Exception
            AddInfo("db imp fail:" & ex.Message)
        End Try
    End Sub

    Private Function updateDbList() As Dictionary(Of String, Long)
        Dim dbList As New Dictionary(Of String, Long)
        Dim connectionString As String = $"Data Source={dbPath};Version=3;"
        Try
            Using conn As New SQLite0.SQLiteConnection(connectionString)


                Dim selectSql As String = "SELECT TradeDate,StockCode FROM TradeList group by TradeDate,StockCode"
                Using cmd As New SQLite0.SQLiteCommand(selectSql, conn)
                    Using reader As SQLite0.SQLiteDataReader = cmd.ExecuteReader()
                        While reader.Read()
                            dbList.Add($"{reader("TradeDate")}-{reader("StockCode")}", 1)
                        End While
                    End Using
                End Using
            End Using
        Catch ex As Exception
            AddInfo("dbList fail:" & ex.Message)
        End Try
        Return dbList
    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        '初始化数据库
        Try

            Dim db = New SQLiteConnection(dbPath)

            db.CreateTable(Of DailyStats)()
            db.CreateTable(Of TradeSummary)()

            db.Close()
        Catch ex As Exception
            AddInfo("db Init fail:" & ex.Message)
        End Try

        Try
            ' 初始化列表视图
            InitLogListView(ListView)
            '
            ' 配置BackgroundWorker
            bgWorkerImpFile.WorkerReportsProgress = True
            bgWorkerImpFile.WorkerSupportsCancellation = True
            ' 绑定事件处理程序
            AddHandler bgWorkerImpFile.DoWork, AddressOf bgWorkerImpFile_DoWork
            AddHandler bgWorkerImpFile.ProgressChanged, AddressOf bgWorkerImpFile_ProgressChanged
            AddHandler bgWorkerImpFile.RunWorkerCompleted, AddressOf bgWorkerImpFile_RunWorkerCompleted
        Catch ex As Exception
            AddInfo("Form Init fail:" & ex.Message)
        End Try

        '初始化日期
        TbDateSta.Text = DateTime.Now.AddDays(-90).ToString("yyyy-MM-dd")
        TbDateEnd.Text = DateTime.Now.ToString("yyyy-MM-dd")

    End Sub

    Private Sub bgWorkerImpFile_DoWork(sender As Object, e As DoWorkEventArgs)
        Dim args As ImportArguments = CType(e.Argument, ImportArguments)
        Dim db As SQLiteConnection = Nothing
        Try
            db = New SQLiteConnection(dbPath)
            ImportFiles(db, args.Files, args.IsFirstLine)
        Catch ex As Exception
            e.Result = ex.Message
        Finally
            If db IsNot Nothing Then db.Close()
        End Try
    End Sub

    Private Sub bgWorkerImpFile_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
        ' 更新进度条
        Try
            If ProgressBar1.InvokeRequired Then
                ProgressBar1.Invoke(Sub()
                                        ProgressBar1.Value = e.ProgressPercentage
                                    End Sub)
            Else
                ProgressBar1.Value = e.ProgressPercentage
            End If
        Catch ex As Exception
            AddInfo("进度条参数问题:" & ex.Message)
        End Try

        ' 添加日志信息
        Dim logMessage As String = CType(e.UserState, String)
        If Not String.IsNullOrEmpty(logMessage) Then
            AddInfo(logMessage)
        End If
    End Sub

    Private Sub bgWorkerImpFile_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
        If e.Result IsNot Nothing Then
            AddInfo("import err:" & e.Result)
        ElseIf e.Cancelled Then
            AddInfo("import cancelled")
        Else
            AddInfo("import completed")
            'DataCount()
        End If
    End Sub
    Sub ImportFiles(ByVal db As SQLiteConnection, ByVal fList As String(), Optional isFirstLine As Boolean = True)

        If fList IsNot Nothing Then

                Dim tSta As DateTime = DateTime.Now
                ' 设置进度条
                bgWorkerImpFile.ReportProgress(0, "Start Import data into database")
                ProgressBar1.Invoke(Sub()
                                        ProgressBar1.Minimum = 0
                                        ProgressBar1.Maximum = fList.Length
                                        ProgressBar1.Value = 0
                                        ProgressBar1.Step = 1
                                    End Sub)

                '插入数据库 临时
                For i As Integer = 0 To fList.Length - 1
                    Dim progress As Integer = i + 1
                    bgWorkerImpFile.ReportProgress(progress, $"Processing file {i + 1}/{fList.Length}") ': {Path.GetFileName(file)}
                    Dim file As String = fList(i)
                    ImportDataFromFile(db, file, isFirstLine)
                Next

                'bgWorkerImpFile.ReportProgress(fList.Length - 1, "Import completed")
                ProgressBar1.Invoke(Sub()
                                        ProgressBar1.Value = ProgressBar1.Maximum
                                    End Sub)

                '
                Dim tCost As TimeSpan = DateTime.Now - tSta
                Dim tCostStr As String = String.Format("{0:00}:{1:00}:{2:00}", Math.Floor(tCost.TotalHours), tCost.Minutes, tCost.Seconds)
                ListView.Invoke(Sub()
                                    AddInfo("Import " & fList.Length & " files into database done! Cost " & tCostStr)
                                End Sub)

            Else
                MsgBox("No files selected.")
                AddInfo("Err : No files selected.")
            End If

    End Sub


    ' 导入数据
    Sub ImportDataFromFile(ByVal db As SQLiteConnection, filePath As String, Optional isFirstLine As Boolean = True)
        Try
            db.CreateTable(Of TradeList)()

            Dim tel As String
            Dim DbList As New List(Of TradeList)
            Dim fields As String()
            Dim tels As New List(Of String)
            Dim price As Double = 0


            '原始数量
            'Dim countStart As Long = db.Table(Of DbTabA).Count()
            'Dim countStart As Long = db.ExecuteScalar(Of Long)($"SELECT count(Tel) FROM DbTab{dbInto}")
            Dim tradeDateStr = Path.GetDirectoryName(filePath)?.Split(Path.DirectorySeparatorChar).Last()
            ' 更新进度条:显示处理的文件信息
            ListView.Invoke(Sub()
                                AddInfo($"open:{tradeDateStr}:{Path.GetFileName(filePath)}")
                            End Sub)

            ' 获取交易日期
            Dim tradeDate = DateTime.ParseExact(tradeDateStr, "yyyy-MM-dd", Nothing)
            Dim tradeCode = Path.GetFileNameWithoutExtension(filePath)

            ' 检查数据库中是否有数据
            ListView.Invoke(Sub()
                                AddInfo($"删除已有数据{tradeDateStr}-{tradeCode}")
                            End Sub)
            'If dbDateDic.ContainsKey($"{tradeDateStr}-{tradeCode}") Then
            '删除明细
            db.Execute($"delete FROM TradeSummary where StockCode='{tradeCode}' and TradeDate='{tradeDateStr}'")
            '删除合计值
            db.Execute($"delete FROM DailyStats where StockCode='{tradeCode}' and TradeDate='{tradeDateStr}'")
            'End If
            Using reader As New StreamReader(filePath)
                While Not reader.EndOfStream
                    '
                    tel = reader.ReadLine
                    tel = tel.Trim(" "c)
                    fields = tel.Split(","c)
                    If isFirstLine Then
                        isFirstLine = False
                    Else
                        price = fields(2)
                        DbList.Add(New TradeList(tradeCode, tradeDateStr, price, fields(3)))
                    End If
                End While
            End Using

            Dim countAdd As Long = DbList.Count
            dbListCount += countAdd ' 累计插入数据
            ListView.Invoke(Sub()
                                AddInfo($"插入数据:{countAdd}")
                            End Sub)

            db.InsertAll(DbList)

            Dim TotalAmount As Double = db.ExecuteScalar(Of Double)($"SELECT sum(Amount) FROM TradeList")
            db.Insert(New DailyStats(tradeCode, tradeDateStr, price, TotalAmount))
            db.Execute("INSERT OR IGNORE INTO 
            TradeSummary (StockCode,TradeDate,AmountRange,TotalAmount) 
            SELECT StockCode,TradeDate,AmountRange,sum(Amount) as TotalAmount 
            FROM TradeList 
            group by StockCode,TradeDate,AmountRange
        ")
            '
            db.DropTable(Of TradeList)()
        Catch ex As Exception
            ListView.Invoke(Sub()
                                AddInfo($"err:{ex.Message   }")
                                AddInfo($"err:{ex.StackTrace}")
                                AddInfo($"err:{ex.InnerException.Message}")
                            End Sub)
        End Try
    End Sub
    ' 更新板块信息
    Sub ImportStockBlock(ByVal db As SQLiteConnection, filePath As String, Optional isFirstLine As Boolean = True)
        db.DropTable(Of StockBlock)()
        db.CreateTable(Of StockBlock)()
        '
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) '下面 getEncoding("GB2312") 需要的前置代码

        Dim s As String
        Dim fields As String()
        Dim DbList As New List(Of StockBlock)


        ListView.Invoke(Sub()
                            AddInfo("open:" & Path.GetFileName(filePath))
                        End Sub)

        ' 获取交易日期
        Using reader As New StreamReader(filePath, encoding:=Encoding.GetEncoding("GB2312"))
            While Not reader.EndOfStream
                '
                s = reader.ReadLine
                fields = s.Split(",")
                If isFirstLine Then
                    isFirstLine = False
                Else
                    DbList.Add(New StockBlock(fields(0), fields(1), fields(2)))
                End If
            End While
        End Using

        Dim countAdd As Long = DbList.Count


        db.InsertAll(DbList)
        AddInfo("Import StockBlock success!")
    End Sub
    ' 更新金额范围信息
    Sub ImportAmountRangeList(ByVal db As SQLiteConnection, filePath As String, Optional isFirstLine As Boolean = True)
        db.DropTable(Of AmountRangeList)()
        db.CreateTable(Of AmountRangeList)()
        '
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) '下面 getEncoding("GB2312") 需要的前置代码

        Dim s As String
        Dim fields As String()
        Dim DbList As New List(Of AmountRangeList)


        ListView.Invoke(Sub()
                            AddInfo("open:" & Path.GetFileName(filePath))
                        End Sub)

        ' 获取交易日期
        Using reader As New StreamReader(filePath, encoding:=Encoding.GetEncoding("GB2312"))
            While Not reader.EndOfStream
                '
                s = reader.ReadLine
                fields = s.Split(",")
                If isFirstLine Then
                    isFirstLine = False
                Else
                    DbList.Add(New AmountRangeList(fields(0), fields(1), fields(2)))
                End If
            End While
        End Using

        Dim countAdd As Long = DbList.Count


        db.InsertAll(DbList)
        AddInfo("Import AmountRangeList success!")
    End Sub

    Private Sub Bt_Imp_Block_Click(sender As Object, e As EventArgs) Handles Bt_Imp_Block.Click
        selectedFiles = PickFile(Me.OpenFileDialog1, "csv", False)
        Dim stockBlockFile As String = String.Empty
        If selectedFiles.Length > 0 Then
            stockBlockFile = selectedFiles(0)
        Else
            AddInfo("No file select")
            Exit Sub
        End If

        Dim db As SQLiteConnection = Nothing

        db = New SQLiteConnection(dbPath)

        ImportStockBlock(db, stockBlockFile)
    End Sub

    Private Sub BtImpAmoutRange_Click(sender As Object, e As EventArgs) Handles BtImpAmoutRange.Click
        selectedFiles = PickFile(Me.OpenFileDialog1, "csv", False)
        Dim ImpFile As String = String.Empty
        If selectedFiles.Length > 0 Then
            ImpFile = selectedFiles(0)
        Else
            AddInfo("No file select")
            Exit Sub
        End If

        Dim db As SQLiteConnection = Nothing

        db = New SQLiteConnection(dbPath)

        ImportAmountRangeList(db, ImpFile)
    End Sub

    Private Sub BtExpData_Click(sender As Object, e As EventArgs) Handles BtExpData.Click

        '
        expDbBlcok()
    End Sub


    Private Sub TbDateSta_LostFocus(sender As Object, e As EventArgs) Handles TbDateSta.LostFocus
        Dim dateStaStr As String = TbDateSta.Text

        If dateStaStr.Length = 0 Then
            AddInfo("没有输入开始日期")
            Exit Sub
        ElseIf Not IsDate(dateStaStr) Then
            AddInfo($"日期无效{dateStaStr}")
            '
            TbDateSta.Focus()
            TbDateSta.SelectAll()
            Exit Sub
        End If
        Dim dateSta = CDate(dateStaStr)
        Dim dateEnd = dateSta.AddDays(90)
        TbDateSta.Text = dateSta.ToString("yyyy-MM-dd")

        '
        Dim dateEndStr As String = TbDateEnd.Text
        If dateEndStr.Length = 0 Or IsDate(dateEndStr) = False Then
            ' 没有录入结束日期
            TbDateEnd.Text = dateEnd.ToString("yyyy-MM-dd")
            AddInfo("没有输入结束日期或结束日期异常,结束日期初始化")
            Exit Sub
        ElseIf CDate(dateEndStr) > dateEnd Then
            '判断结束日期是否超期
            ' 没有录入结束日期
            TbDateEnd.Text = dateEnd.ToString("yyyy-MM-dd")
            AddInfo("日期跨度超过90天")
            Exit Sub
        End If
    End Sub



    Private Sub TbDateEnd_LostFocus(sender As Object, e As EventArgs) Handles TbDateEnd.LostFocus
        Dim dateEndStr As String = TbDateEnd.Text '结束日期
        Dim dateStaStr As String = TbDateSta.Text '开始日期
        If dateEndStr.Length = 0 Then
            AddInfo("没有输入结束日期")
            Exit Sub
        ElseIf Not IsDate(dateEndStr) Then
            AddInfo($"结束日期输入无效{dateEndStr}")
            Exit Sub
        ElseIf IsDate(dateStaStr) Then
            Dim dateSta = CDate(dateStaStr)
            Dim dateEnd = CDate(dateEndStr)
            Dim dateXz = dateSta.AddDays(90)
            If dateEnd > dateXz Then
                AddInfo($"结束日期超出开始日期90天")
                TbDateEnd.Text = dateXz.ToString("yyyy-MM-dd")
            End If
        End If
    End Sub
    Sub expDbBlcok()
        Dim filePath As String = Path.Combine(Application.StartupPath, "exp", "Block", $"Block_list_{TbDateSta.Text}-{TbDateEnd.Text}.xlsx")
        Directory.CreateDirectory(Path.GetDirectoryName(filePath))
        Try
            ' 检查文件是否存在，如果存在则删除
            If File.Exists(filePath) Then
                File.Delete(filePath)
            End If
            ' 连接到 SQLite 数据库
            Dim db = New SQLiteConnection(dbPath)
            Dim data = db.Table(Of BlockRangeSummary)().ToList()

            ' 动态获取所有唯一的 RangeName 作为列名
            Dim rangeNames = data.Select(Function(x) x.RangeName).Distinct().ToList()
            Dim BlockNames = data.Select(Function(x) x.BlockName).Distinct().ToList()
            Dim TradeDates = data.Select(Function(x) x.TradeDate).Distinct().ToList()

            '
            Dim sheets As New Dictionary(Of String, Object)
            For Each BlockName In BlockNames
                Dim dataTmp = data.Where(Function(d) d.BlockName = BlockName).ToList()
                ' 重置数据表
                Dim dt = New DataTable()
                dt.Columns.Add("TradeDate", GetType(String))
                For Each rangeName In rangeNames
                    dt.Columns.Add(rangeName, GetType(Double))
                Next
                '
                For Each TradeDate In TradeDates
                    Dim newRow = dt.NewRow()
                    Dim dataTmpDate = dataTmp.Where(Function(d) d.TradeDate = TradeDate).ToList()
                    newRow("TradeDate") = TradeDate
                    For Each rangeName In rangeNames
                        newRow(rangeName) = dataTmpDate.Where(Function(d) d.RangeName = rangeName).ToList().Average(Function(d) d.RangeRate)
                    Next
                    dt.Rows.Add(newRow)
                Next
                '
                sheets.Add(BlockName, dt)
            Next
            MiniExcel.SaveAs(filePath, sheets)
            AddInfo($"板块已成功导出到 {filePath}.xlsx")
        Catch ex As Exception
            AddInfo(ex.Message)
        End Try




        '        ' 构建 SQL 查询语句
        '        Dim sql As String = "DROP TABLE IF EXISTS PivotTable;
        'CREATE TABLE new_table_name AS 
        'SELECT BlockName, TradeDate"
        '        For Each rangeName In rangeNames
        '            sql += $", SUM(CASE WHEN RangeName = '{rangeName}' THEN RangeRate ELSE 0 END) AS [{rangeName}]"
        '        Next
        '        sql += " FROM BlockRangeSummary GROUP BY BlockName, TradeDate"

        '        db.Execute(sql)
        ' 导出EXCEL
        'Dim resultList = New List(Of Dictionary(Of String, Object))()
        '' 使用 MiniExcel 将数据写入 Excel 文件
        'MiniExcel.SaveAs(filePath, resultList)


    End Sub
    Sub expDbStock()
        Dim StockCodeNeed As String = TbStockCode.Text
        Dim filePath As String = Path.Combine(Application.StartupPath, "exp", "Stock", $"Stock_list_{TbDateSta.Text}-{TbDateEnd.Text}-{StockCodeNeed}.xlsx")
        Directory.CreateDirectory(Path.GetDirectoryName(filePath))
        Try
            ' 检查文件是否存在，如果存在则删除
            If File.Exists(filePath) Then
                File.Delete(filePath)
            End If
            ' 连接到 SQLite 数据库
            Dim db = New SQLiteConnection(dbPath)
            Dim data = db.Table(Of StockRangeSummary)().Where(Function(d) d.StockCode = StockCodeNeed).ToList()

            ' 动态获取所有唯一的 RangeName 作为列名
            Dim rangeNames = data.Select(Function(x) x.RangeName).Distinct().ToList()
            Dim StockCodes = data.Select(Function(x) x.StockCode).Distinct().ToList()
            Dim TradeDates = data.Select(Function(x) x.TradeDate).Distinct().ToList()

            '
            Dim sheets As New Dictionary(Of String, Object)
            For Each StockCode In StockCodes
                Dim dataTmp = data.Where(Function(d) d.StockCode = StockCode).ToList()
                ' 重置数据表
                Dim dt = New DataTable()
                dt.Columns.Add("TradeDate", GetType(String))
                For Each rangeName In rangeNames
                    dt.Columns.Add(rangeName, GetType(Double))
                Next
                '
                For Each TradeDate In TradeDates
                    Dim newRow = dt.NewRow()
                    Dim dataTmpDate = dataTmp.Where(Function(d) d.TradeDate = TradeDate).ToList()
                    newRow("TradeDate") = TradeDate
                    For Each rangeName In rangeNames
                        newRow(rangeName) = dataTmpDate.Where(Function(d) d.RangeName = rangeName).ToList().Sum(Function(d) d.RangeRate)
                    Next
                    dt.Rows.Add(newRow)
                Next
                '
                sheets.Add(StockCode, dt)
            Next
            MiniExcel.SaveAs(filePath, sheets)
            AddInfo($"股票已成功导出到 {filePath}.xlsx")
        Catch ex As Exception
            AddInfo(ex.Message)
        End Try




        '        ' 构建 SQL 查询语句
        '        Dim sql As String = "DROP TABLE IF EXISTS PivotTable;
        'CREATE TABLE new_table_name AS 
        'SELECT BlockName, TradeDate"
        '        For Each rangeName In rangeNames
        '            sql += $", SUM(CASE WHEN RangeName = '{rangeName}' THEN RangeRate ELSE 0 END) AS [{rangeName}]"
        '        Next
        '        sql += " FROM BlockRangeSummary GROUP BY BlockName, TradeDate"

        '        db.Execute(sql)
        ' 导出EXCEL
        'Dim resultList = New List(Of Dictionary(Of String, Object))()
        '' 使用 MiniExcel 将数据写入 Excel 文件
        'MiniExcel.SaveAs(filePath, resultList)


    End Sub
    '
    Sub JiSuan()
        '检查日期范围
        Dim dayStaStr As String = TbDateSta.Text
        Dim dayEndStr As String = TbDateEnd.Text
        Dim daySta As DateTime
        Dim dayEnd As DateTime

        Try
            If dayStaStr.Length = 0 Then
                AddInfo("开始日期为空")
                MsgBox("开始日期不可为空")
                Exit Sub
            Else
                daySta = DateTime.ParseExact(dayStaStr, "yyyy-MM-dd", Nothing)
            End If

            If dayEndStr.Length = 0 Then
                dayEnd = daySta.AddDays(90)
                dayEndStr = dayEnd.ToString("yyyy-MM-dd")
                TbDateEnd.Text = dayEndStr
            Else
                dayEnd = DateTime.ParseExact(dayEndStr, "yyyy-MM-dd", Nothing)
            End If

            Dim db = New SQLiteConnection(dbPath)
            db.DropTable(Of StockRangeSummary)()
            db.CreateTable(Of StockRangeSummary)()
            '
            db.DropTable(Of BlockRangeSummary)()
            db.CreateTable(Of BlockRangeSummary)()

            ' 逐个方案

            Dim dbAmountRangList = db.Query(Of AmountRangeList)("select * from AmountRangeList")
            For Each record In dbAmountRangList
                ' 计算范围占比
                Dim sql As String = $"INSERT OR IGNORE INTO 
        StockRangeSummary(StockCode,TradeDate,RangeName,RangeTotalAmount,StockTotalAmount,RangeRate)
        select a.StockCode,a.TradeDate,a.RangeName,a.RangeTotalAmount,DailyStats.TotalAmount as StockTotalAmount,a.RangeTotalAmount/DailyStats.TotalAmount*100 as RangeRate
        from(
        select StockCode,TradeDate,'{record.RangeName}' as RangeName,sum(totalAmount) as RangeTotalAmount
        from TradeSummary
 where AmountRange >=  {record.RangeMin} and AmountRange<={record.RangeMax} and DATE(TradeDate)>='{dayStaStr}' and DATE(TradeDate)<='{dayEndStr}'
        group by StockCode,TradeDate,'{record.RangeName}'
 ) as a join DailyStats on a.StockCode = DailyStats.StockCode and a.TradeDate = DailyStats.TradeDate"
                db.Execute(sql)
            Next

            db.Execute($"INSERT OR IGNORE INTO 
        StockRangeSummary(StockCode,TradeDate,RangeName,RangeRate)
        select StockCode,TradeDate,'收盘价', CLostPrice
        from DailyStats
        where DATE(TradeDate)>='{dayStaStr}' and DATE(TradeDate)<='{dayEndStr}'
        ")

            '计算板块占比
            db.Execute(
                "INSERT OR IGNORE INTO 
        BlockRangeSummary(BlockName,TradeDate,RangeName,RangeRate)
        select StockBlock.BlockName,StockRangeSummary.TradeDate,StockRangeSummary.RangeName,avg(StockRangeSummary.RangeRate) as RangeRate
        from StockBlock join StockRangeSummary  on StockBlock.StockCode = StockRangeSummary.StockCode
        group by StockBlock.BlockName,StockRangeSummary.TradeDate,StockRangeSummary.RangeName"
                )


            '        '收盘价
            '        db.Execute(
            '           $"INSERT OR IGNORE INTO 
            'BlockRangeSummary(BlockName,TradeDate,RangeName,RangeRate)
            'select StockBlock.BlockName,DailyStats.TradeDate,'收盘价',avg(DailyStats.CLostPrice) as CLostPrice
            'from StockBlock join DailyStats  on StockBlock.StockCode = DailyStats.StockCode
            'where DATE(TradeDate)>='{dayStaStr}' and DATE(TradeDate)<='{dayEndStr}'
            'group by StockBlock.BlockName,DailyStats.TradeDate,'收盘价'"
            '            )


            db.Close()
            AddInfo("计算完成")
        Catch ex As Exception
            AddInfo($"错误:{ex.Message}")
        End Try
    End Sub

    Private Sub BtJiSuan_Click(sender As Object, e As EventArgs) Handles BtJiSuan.Click
        JiSuan()
        expDbBlcok()
    End Sub

    Private Sub BtExpStockData_Click(sender As Object, e As EventArgs) Handles BtExpStockData.Click
        expDbStock()
    End Sub
End Class
Class ImportArguments
    Public Property IsFirstLine As Boolean
    Public Property DbInto As String
    Public Property Files As String()
End Class
